import { http } from '@/utils/http'

class DictCache {
  private cache: Map<string, any[]> = new Map()
  private loadingPromises: Map<string, Promise<any>> = new Map()

  async getDictItems(dictCode: string): Promise<any[]> {
    // 如果缓存中已有数据，直接返回
    if (this.cache.has(dictCode)) {
      return this.cache.get(dictCode)!
    }

    // 如果正在加载中，返回同一个Promise
    if (this.loadingPromises.has(dictCode)) {
      return this.loadingPromises.get(dictCode)!
    }

    // 发起请求并缓存Promise
    const promise = http
      .get(`/sys/dict/getDictItems/${dictCode}`)
      .then((res) => {
        const data = res.result || []
        this.cache.set(dictCode, data)
        this.loadingPromises.delete(dictCode)
        return data
      })
      .catch((error) => {
        console.error(`获取字典数据失败: ${dictCode}`, error)
        this.loadingPromises.delete(dictCode)
        return []
      })

    this.loadingPromises.set(dictCode, promise)
    return promise
  }

  // 清除缓存
  clearCache(dictCode?: string) {
    if (dictCode) {
      this.cache.delete(dictCode)
    } else {
      this.cache.clear()
    }
  }
}

export const dictCache = new DictCache()
